package com.mango.community.controller;

import com.mango.community.entity.Event;
import com.mango.community.entity.User;
import com.mango.community.event.EventProducer;
import com.mango.community.service.LikeService;
import com.mango.community.util.CommunityConstant;
import com.mango.community.util.CommunityUtil;
import com.mango.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/8/15 23:54
 * 点赞的controller
 */
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;

    /** 点赞的方法   返回数据即可
     * @param entityType
     * @param entityId
     * @param entityUserId 帖子的用户id
     * @param postId  帖子的id
     * @return
     */
    @PostMapping("/like")
    @ResponseBody
    public String like(int entityType,int entityId,int entityUserId,int postId){
        //获取当前用户
        User user = hostHolder.getUser();
        //点赞的实现
        likeService.like(user.getId(),entityType,entityId,entityUserId);
        //点赞的数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        //点赞的状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(),entityType,entityId);
        //返回的结果
        Map<String,Object> map = new HashMap<>();
        map.put("likeCount",likeCount);
        map.put("likeStatus",likeStatus);

        //触发点赞
        //只有当点赞的时候才触发 ，取消点赞不触发
        if (likeStatus == 1){
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(hostHolder.getUser().getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId",postId);
            eventProducer.fireEvent(event);
        }

        //返回给页面
        return CommunityUtil.getJSONString(0,null,map);
    }
}
